#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import sys
import time
import socket
import fcntl
import struct
import threading

def log_err(message):
    err_msg = '[%s] %s' % (time.ctime(), message)
    sys.stderr.write(err_msg)

def log_out(message):
    out_msg = '[%s] %s' % (time.ctime(), message)
    sys.stdout.write(out_msg)

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])

def nfs_mkdirs(path):
    try:
        if not os.path.exists(path):
            os.umask(0)
            os.makedirs(path)
    except OSError, e:
        log_err('Mkdir [%s] error [%d]: %s' % (path, e.errno, e.strerror))
        pass

class Atomic:
    def __init__(self, value):
        self.lock = threading.Lock()
        self.value = value
    
    def get(self):
        self.lock.acquire()
        tmp = self.value
        self.lock.release()
        return tmp

    def set(self, value):
        self.lock.acquire()
        self.value = value
        self.lock.release()

    def increment_and_get(self):
        self.lock.acquire()
        self.value += 1
        tmp = self.value
        self.lock.release()
        return tmp

    def get_and_increment(self):
        self.lock.acquire()
        tmp = self.value
        self.value += 1
        self.lock.release()
        return tmp

